package com.solocredit.finance.ui.steps.act

import android.graphics.Color
import android.view.View
import androidx.camera.core.AspectRatio
import androidx.camera.core.CameraSelector
import androidx.camera.core.ImageCapture
import androidx.camera.core.ImageCaptureException
import androidx.camera.core.Preview
import androidx.camera.lifecycle.ProcessCameraProvider
import androidx.core.content.ContextCompat
import com.solocredit.finance.app.MyApp
import com.solocredit.finance.base.utils.ImageUtil
import com.solocredit.finance.base.utils.TitleBarUtil
import com.solocredit.finance.base.utils.log.MullaLog
import com.solocredit.finance.databinding.ActMullaCameraOcrBinding
import com.solocredit.finance.http.HttpHelper
import com.solocredit.finance.mvp.MvpAct
import com.solocredit.finance.ui.steps.impl.MullaUploadPresenterImpl
import com.solocredit.finance.ui.steps.view.IMullaUploadView
import com.solocredit.finance.utils.event.MullaEventType
import com.solocredit.finance.utils.helper.MullaCustomConfigsHelper
import com.solocredit.finance.utils.imagecovert.ImageConvert
import java.io.File
import java.util.concurrent.ExecutorService
import java.util.concurrent.Executors

/**
 * MullaFlow
 * @Author wwdeng
 * @CreateTime: 2024/7/31 11:15
 * @Annotation：身份证、驾驶证、护照拍照
 */
class MullaCameraOcrAct: MvpAct<IMullaUploadView, MullaUploadPresenterImpl>(),IMullaUploadView {
    private var _binding: ActMullaCameraOcrBinding? = null
    private val binding get() = _binding ?: throw IllegalStateException(
        "camera ocr binding because it is null. Either the view hasn't been created yet, or it has already been destroyed."
    )

    private var cameraExecutor: ExecutorService? = null
    private var imageCapture: ImageCapture? = null
    private var imgUsePath = ""

    override fun createPresenter(): MullaUploadPresenterImpl {
        return MullaUploadPresenterImpl(this)
    }

    override fun getMullaRootView(): View {
        _binding = ActMullaCameraOcrBinding.inflate(layoutInflater)
        return binding.root
    }

    override fun initMullaView() {
        TitleBarUtil.setStatusBarLightMode(this, false)
        _binding?.titleLayout?.setPadding(0, TitleBarUtil.getStatusBarHeight(),0,0)

        cameraExecutor = Executors.newSingleThreadExecutor()
        startCamera()
    }

    override fun initMullaListener() {
        _binding?.imgBack?.setOnClickListener {
            finish()
        }

        //客服
        _binding?.imgKefu?.setOnClickListener {
            showMullaKefuDialog("OcrCamera Page")
            HttpHelper.addMullaEventAction(MullaEventType.CLICK.MULLA_CLICK_CUSTOMER,"OcrCamera Page")
        }

        //拍照
        _binding?.imgTakeCamera?.setOnClickListener {
            HttpHelper.addMullaEventAction(MullaEventType.CLICK.MULLA_CLICK_CAMERA_TAKE_PHOTO,"OcrCamera Page")
            takeFilePhoto()
        }

        //重拍
        _binding?.remakeLayout?.setOnClickListener {
            HttpHelper.addMullaEventAction(MullaEventType.CLICK.MULLA_CLICK_STEP_OCR_UPLOAD_RETAKE,"OcrCamera Page")
            showTakeView()
        }

        //使用
        _binding?.usePhotoLayout?.setOnClickListener {
            HttpHelper.addMullaEventAction(MullaEventType.CLICK.MULLA_CLICK_STEP_OCR_UPLOAD_USE_PHOTO,"OcrCamera Page")
            showMullaLoading(isTOuchOut = false, isCancel = false)
            presenter.onMullaUploadImageAction(imgUsePath)
        }
    }

    override fun initMullaData() {
        _binding?.let { binding ->
            //牌照信息
            val licenseInfo = MullaCustomConfigsHelper.getMullaLicenseInfo()
            if (licenseInfo == null){
                binding.licenseLayout.visibility = View.GONE
            } else {
                binding.licenseLayout.visibility = View.VISIBLE
                ImageUtil.instance?.loadImageUrl(this,binding.imgLicenseLogo, licenseInfo.optString("logo"))
                binding.textLicenseDesc.text = licenseInfo.optString("desc")
                binding.textLicenseValue.text = licenseInfo.optString("companyName")
            }
        }
    }

    /**
     * 打开相机预览
     */
    private fun startCamera() {
        showTakeView()
        val cameraProviderFuture = ProcessCameraProvider.getInstance(this)
        cameraProviderFuture.addListener(Runnable {
            val cameraProvider: ProcessCameraProvider = cameraProviderFuture.get()
            val preview = Preview.Builder()
                .setTargetAspectRatio(AspectRatio.RATIO_16_9)
                .build()
                .also {
                    it.setSurfaceProvider(_binding?.carmeraView?.surfaceProvider)
                }
            imageCapture = ImageCapture.Builder().build()
            //打开后置摄像头
            val cameraSelector = CameraSelector.DEFAULT_BACK_CAMERA
            try {
                cameraProvider.unbindAll()
                cameraProvider.bindToLifecycle(this, cameraSelector, preview,imageCapture)
            } catch(exc: Exception) {
            }
        }, ContextCompat.getMainExecutor(this))
    }

    /**
     * 拍照并保存到本地
     */
    private fun takeFilePhoto(){
        if (imageCapture != null){
            //创建文件
            val filePath = MyApp.app.filesDir.absolutePath
            val outputFile = File(filePath,"${System.currentTimeMillis()}.jpg")
            if (!outputFile.exists()){
                outputFile.mkdir()
            }
            //创建输出选项对象
            val metadata = ImageCapture.Metadata()
//            metadata.isReversedHorizontal = true
            //创建文件
            val outputFileOptions = ImageCapture.OutputFileOptions.Builder(outputFile).setMetadata(metadata).build()
            //开始拍照
            imageCapture?.takePicture(outputFileOptions, ContextCompat.getMainExecutor(this),object : ImageCapture.OnImageSavedCallback{
                override fun onImageSaved(outputFileResults: ImageCapture.OutputFileResults) {
                    val imgUri = outputFileResults.savedUri

                    MullaLog.e("take photo complete>>>>>>>${imgUri?.path}")
                    // 图片处理
                    ImageConvert.covert(context = this@MullaCameraOcrAct, uri = imgUri) { localPath, bitmap ->
                        if (localPath != null){
                            imgUsePath = localPath
                            MullaLog.e("imageConvert success>>>>>>>$localPath")
                            showCompleteView()
                        }
                    }
                }
                override fun onError(exception: ImageCaptureException) {
                    MullaLog.e("take photo failed>>>>>>>${exception.message}")
                }
            })
        }
    }

    /**
     * 显示拍照样式
     */
    private fun showTakeView(){
        _binding?.let { binding ->
            binding.maskView.setMaskColor(Color.parseColor("#80000000"))
            binding.imgPreview.visibility = View.GONE
            binding.imgTakeCamera.visibility = View.VISIBLE
            binding.takeAfterLayout.visibility = View.GONE
        }
    }

    /**
     * 显示拍照完成页面
     */
    private fun showCompleteView(){
        _binding?.let { binding ->
            ImageUtil.instance?.loadImageUrl(this@MullaCameraOcrAct,binding.imgPreview,imgUsePath)
            binding.maskView.setMaskColor(Color.parseColor("#000000"))
            binding.imgPreview.visibility = View.VISIBLE
            binding.imgTakeCamera.visibility = View.INVISIBLE
            binding.takeAfterLayout.visibility = View.VISIBLE
        }
    }

    /**
     * 图片上传完成
     */
    override fun showMullaUploadImageSuccess(imgPath: String, imgUrl: String) {
        val intent = intent
        intent.putExtra("imgLocalPath",imgPath)
        intent.putExtra("imgUrl",imgUrl)
        setResult(RESULT_OK,intent)
        finish()
    }

    override fun onStart() {
        super.onStart()
        HttpHelper.addMullaEventAction(MullaEventType.PAGE.MULLA_PAGE_STEP_OCR_CAMERA_START,"")
    }

    override fun onDestroy() {
        super.onDestroy()
        _binding = null
        HttpHelper.addMullaEventAction(MullaEventType.PAGE.MULLA_PAGE_STEP_OCR_CAMERA_END,"")
        cameraExecutor?.shutdown()
    }
}